package cn.edu.fzu.homemaking.company.handler.impl;

import cn.edu.fzu.homemaking.company.domain.entity.CompanyUser;
import cn.edu.fzu.homemaking.company.domain.entity.Order;
import cn.edu.fzu.homemaking.company.handler.OrderError;
import cn.edu.fzu.homemaking.company.handler.OrderHandler;
import cn.edu.fzu.homemaking.company.handler.OrderSession;
import cn.edu.fzu.homemaking.company.service.OrdersCompanyUserService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Random;

@Component("orderUserAllotHandler")
public class OrderUserAllotHandler implements OrderHandler {

    @Resource
    private OrdersCompanyUserService ordersCompanyUserService;

    @Override
    public boolean process(OrderSession session) {
        Order order = session.order;
        List<CompanyUser> companyUsers = session.companyUsers;
        int userCount = 1;
        if (session.demand != null) {
            userCount = session.demand.getPerson();
        }
        if (companyUsers.size() < userCount) {
            session.error = OrderError.NO_ENOUGH_USER;
            return false;
        }
        for (int i = 0; i < userCount; i++) {
            Random random = new Random();
            //从服务员中随机选一个
            int index = random.nextInt(companyUsers.size());
            CompanyUser user = companyUsers.get(index);
            ordersCompanyUserService.add(order.getOrderId(), user.getCompanyUserId());
            companyUsers.remove(user);
        }
        return true;
    }
}
